//
//  PersonalCenterViewControllerNew.m
//  homeland
//
//  Created by caesar on 14-3-6.
//  Copyright (c) 2014年 xzysun. All rights reserved.
//

#import "PersonalCenterViewControllerNew.h"
#import "LoginViewController.h"
#import "AdviceChooseCell.h"
#import "AdviceButtonCell.h"
#import "AdviceTextCell.h"
#import "HelpListCell.h"
#import "PersonalInfoViewController.h"
#import "ModifyPasswordViewController.h"
#import "WebViewController.h"
#import "MessageListViewController.h"
#import "RegisterViewController.h"

#define INPUT_VIEW_OFFSET 150.0//常量

@interface PersonalCenterViewControllerNew ()

@property (strong, nonatomic) UIBarButtonItem *rightBt;
//意见反馈里面 星星值
@property (assign, nonatomic) float practicability;
@property (assign, nonatomic) float easeUsablity;

@property (strong, nonatomic) UITextView *adviceTextView;
@property (strong, nonatomic) MessageService *dataService;
@property (assign, nonatomic) BOOL loginFlag;
@end

@implementation PersonalCenterViewControllerNew

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = @"个人中心";
    
    self.dataService = [MessageService new];
    _dataService.delegate = self;
    //    [self initSegment];
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    //控制显示的是登录或者注销
    self.navigationItem.rightBarButtonItem = nil;
    UserInfoService *userService=[UserInfoService getUserInfoService];
    //UserInfo *userInfo=userService.userInfo;
    NSString *currentUserName = userService.currentLoginUserName;
    if (currentUserName && currentUserName.length > 0&&isStart==1) {
        self.navigationItem.rightBarButtonItem = getCustomNavButton(@"注销", self, @selector(rightBtAction:));
        self.loginFlag = YES;
    } else {
        if (isStart==0) {
            self.navigationItem.rightBarButtonItem = getCustomNavButton(@"注册", self, @selector(rightBtAction:));
        }
        if (isStart==2) {
            self.navigationItem.rightBarButtonItem = getCustomNavButton(@"登录", self, @selector(rightBtAction:));
        }
        self.loginFlag = NO;
    }
    [self initSegment];
    //load message
    [_dataService loadMessage];//去掉登录限制
    [self startLoadingViewWithText:@"正在读取消息..."];
    //    if ([UserInfoService getUserInfoService].currentLoginUserName) {
    //        [_dataService loadMessage];//去掉登录限制
    //        [self startLoadingViewWithText:@"正在读取消息..."];
    //    }
    
}
//显视导航条
-(void)initSegment
{
    if (_segmetController) {
        [_segmetController removeFromSuperview];
        _segmetController = nil;
    }
    //init segment
    if (_loginFlag) {
        _segmetController = [[HMSegmentedControl alloc]initWithSectionTitles:[NSArray arrayWithObjects:@"我的消息", @"个人信息", @"意见反馈", @"帮助", nil]];
    } else {
        _segmetController = [[HMSegmentedControl alloc]initWithSectionTitles:[NSArray arrayWithObjects:@"我的消息", @"意见反馈", @"帮助", nil]];
    }
    _segmetController.segmentEdgeInset = UIEdgeInsetsMake(0, 10, 0, 10);
    _segmetController.selectionStyle = HMSegmentedControlSelectionStyleFullWidthStripe;
    _segmetController.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
    //    _segmetController.scrollEnabled = YES;
    [_segmetController setFrame:CGRectMake(0, 0, 320, 44)];
    [_segmetController addTarget:self action:@selector(segmentValueChangedAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:_segmetController];
    [_segmetController setSelectedSegmentIndex:0 animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Button Methods
-(void)rightBtAction:(id)sender
{
    if (isStart==0) {
        RegisterViewController *registerVC = [[RegisterViewController alloc]initWithNibName:@"RegisterViewController" bundle:nil];
        [self.navigationController pushViewController:registerVC animated:YES];
    }
    if (isStart==1) {
        //进行注销
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"是否注销" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
    }
    if (isStart==2) {
        //进行登录
        LoginViewController *loginVC = [[LoginViewController alloc]initWithNibName:@"LoginViewController" bundle:nil];
        [self.navigationController pushViewController:loginVC animated:YES];
    }
}

#pragma mark - Alert Delegate Methods
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
            //取消
            break;
        case 1:
            //注销
            [[UserInfoService getUserInfoService] logout];
            self.navigationItem.rightBarButtonItem = nil;
            self.navigationItem.rightBarButtonItem = getCustomNavButton(@"登录", self, @selector(rightBtAction:));
            self.loginFlag = NO;
            isStart=2;
            [self initSegment];
            break;
        default:
            break;
    }
}

#pragma mark - Segment Method
- (IBAction)segmentValueChangedAction:(id)sender
{
    [self.tableView reloadData];
    NSInteger selected = _segmetController.selectedSegmentIndex;
    if ((_loginFlag && selected == 2)||(!_loginFlag && selected == 0)) {
        //登录状态下的第3个或者非登录状态下的第1个为意见反馈
        self.tableView.scrollEnabled = YES;
    } else {
        self.tableView.scrollEnabled = NO;
    }
}

#pragma mark - Table Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSInteger num = 1;
    if (_loginFlag) {
        //登录状态下，意见反馈是第3个
        if (_segmetController.selectedSegmentIndex == 2) {
            num = 3;//意见反馈那个页面分成三个section
        }
    } else {
        //未登录状态下，意见反馈是第2个
        if (_segmetController.selectedSegmentIndex == 1) {
            num = 3;//意见反馈那个页面分成三个section
        }
    }
    return num;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger num = 0;
    NSInteger selected = _segmetController.selectedSegmentIndex;
    if (selected == 0) {
        //第1个为我的消息
        num = _dataService.dataList.count;
    } else if (_loginFlag && selected == 1) {
        //登录状态下，第2个为个人信息
        num = 2;//个人信息有两项
    } else if ((_loginFlag && selected == 2)||(!_loginFlag && selected == 1)) {
        //登录状态下的第3个或者非登录状态下的第2个为意见反馈
        if (section == 0) {
            num = 2;//意见反馈第一section有2个
        } else {
            num = 1;//意见反馈第二第三section各有1个
        }
    } else if ((_loginFlag && selected == 3)||(!_loginFlag && selected == 2)) {
        //登录状态下的第4个或者非登录状态下的第3个为帮助
        num = 3;//帮助页面有3个
    }
    return num;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger selected = _segmetController.selectedSegmentIndex;
    if ((_loginFlag && selected == 2)||(!_loginFlag && selected == 1)) {
        //登录状态下的第3个或者非登录状态下的第2个为意见反馈
        if (indexPath.section == 1) {
            return 176.0f;//意见反馈的第二个section为4倍高
        }
    }
    return 44.0f;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    NSInteger selected = _segmetController.selectedSegmentIndex;
    if (selected == 0) {
        //第1个为我的消息
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"PersonalTableViewCell"];
        MessageItem *item = [_dataService.dataList objectAtIndex:indexPath.row];
        cell.textLabel.text = item.flmc;
        cell.detailTextLabel.text = item.flsl;
        return cell;
    } else if (_loginFlag && selected == 1) {
        //登录状态下，第2个为个人信息
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"PersonalTableViewCell"];
        if (indexPath.row == 0) {
            cell.textLabel.text = @"我的信息";
        } else {
            cell.textLabel.text = @"密码修改";
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    } else if ((_loginFlag && selected == 2)||(!_loginFlag && selected == 1)) {
        //登录状态下的第3个或者非登录状态下的第2个为意见反馈
        if (indexPath.section == 0) {//第一section选择实用性和易用性
            cell = [[[NSBundle mainBundle]loadNibNamed:@"AdviceChooseCell" owner:self options:nil]objectAtIndex:0];
            if (indexPath.row == 0) {
                ((AdviceChooseCell *)cell).titleLabel.text = @"实用性";
                ((AdviceChooseCell *)cell).starRating.returnBlock = ^(float rate){
                    NSLog(@"实用性打分:%f", rate);
                    self.practicability = rate;
                };
            } else {
                ((AdviceChooseCell *)cell).titleLabel.text = @"易用性";
                ((AdviceChooseCell *)cell).starRating.returnBlock = ^(float rate){
                    NSLog(@"易用性打分:%f", rate);
                    self.easeUsablity = rate;
                };
            }
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        } else if (indexPath.section == 1) {//第二section输入意见
            cell = [[[NSBundle mainBundle]loadNibNamed:@"AdviceTextCell" owner:self options:nil]objectAtIndex:0];
            ((AdviceTextCell *)cell).adviceTextView.inputAccessoryView = [self getInputAccessoryView];
            self.adviceTextView = ((AdviceTextCell *)cell).adviceTextView;
            ((AdviceTextCell *)cell).adviceTextView.delegate = self;
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        } else {//第三section是按钮
            cell = [[[NSBundle mainBundle]loadNibNamed:@"AdviceButtonCell" owner:self options:nil]objectAtIndex:0];
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        return cell;
    } else if ((_loginFlag && selected == 3)||(!_loginFlag && selected == 2)) {
        //登录状态下的第4个或者非登录状态下的第3个为帮助
        cell = [[[NSBundle mainBundle]loadNibNamed:@"HelpListCell" owner:self options:nil]objectAtIndex:0];
        if (indexPath.row == 0) {
            ((HelpListCell *)cell).titleLabel.text = @"帮助";
            ((HelpListCell *)cell).flagImageView.hidden = YES;
        } else if(indexPath.row == 1) {
            ((HelpListCell *)cell).titleLabel.text = @"关于";
            ((HelpListCell *)cell).flagImageView.hidden = YES;
        }
        else if(indexPath.row == 2) {
            ((HelpListCell *)cell).titleLabel.text = @"分享";
            ((HelpListCell *)cell).flagImageView.hidden = YES;
        }
        else {
            ((HelpListCell *)cell).titleLabel.text = @"检查更新";
            ((HelpListCell *)cell).flagImageView.hidden = NO;
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSInteger selected = _segmetController.selectedSegmentIndex;
    if (selected == 0) {
        //第1个为我的消息
        MessageItem *item = [_dataService.dataList objectAtIndex:indexPath.row];
        MessageListViewController *listVC = [[MessageListViewController alloc]initWithNibName:@"MessageListViewController" bundle:nil];
        listVC.listItem = item;
        [self.navigationController pushViewController:listVC animated:YES];
        return;
    } else if (_loginFlag && selected == 1) {
        //登录状态下，第2个为个人信息
        if (indexPath.row == 0) {
            //跳转 我的信息
            PersonalInfoViewController *infoVC = [[PersonalInfoViewController alloc]initWithNibName:@"PersonalInfoViewController" bundle:nil];
            [self.navigationController pushViewController:infoVC animated:YES];
        } else {
            //跳转 密码修改
            ModifyPasswordViewController *modifyVC = [[ModifyPasswordViewController alloc]initWithNibName:@"ModifyPasswordViewController" bundle:nil];
            [self.navigationController pushViewController:modifyVC animated:YES];
        }
        return;
    } else if ((_loginFlag && selected == 2)||(!_loginFlag && selected == 1)) {
        //登录状态下的第3个或者非登录状态下的第2个为意见反馈
        if (indexPath.section == 2) {
            //提交按钮的操作
            [self makeFeedBack];
        }
        return;
    } else if ((_loginFlag && selected == 3)||(!_loginFlag && selected == 1)) {
        //登录状态下的第4个或者非登录状态下的第2个为帮助
        if (indexPath.row == 0) {
            //跳转 帮助页面
            [self showWebView:@"Help"];
        } else if(indexPath.row == 1) {
            //跳转 关于页面
            [self showWebView:@"About"];
        } else if(indexPath.row == 2) {
            //            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms://10086"]];
            if([MFMessageComposeViewController canSendText]){
                [self displaySMSComposeSheet];
            }else{
                NSLog(@"Device not configured to send SMS.");
            }
        }
        else {
            //进行更新检查
        }
        return;
    }
}
#pragma mark - MSM
-(void) displaySMSComposeSheet{
    MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
    picker.messageComposeDelegate=self;
    
    picker.body = @"海珠家园 http://www.haizhu.gov.cn/app/";
    [self presentViewController:picker
                       animated:YES
                     completion:NULL];
}
#pragma mark - MSM2
-(void) messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result{
    
    // Notifies users about errors associated with the interface
    switch (result)
    {
        case MessageComposeResultCancelled:
            NSLog(@"Result: SMS sending canceled");
            break;
        case MessageComposeResultSent:
            NSLog(@"Result: SMS sent");
            break;
        case MessageComposeResultFailed:
            NSLog(@"Result: SMS sending failed");
            break;
        default:
            NSLog(@"Result: SMS not sent");
            break;
    }
    
    [self dismissViewControllerAnimated:YES completion:NULL];
}
#pragma mark - MSM3
-(BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{
    return (toInterfaceOrientation == UIInterfaceOrientationMaskPortrait);
}

#pragma mark - Text View Delegate
//开始输入的时候向上移动整个界面，这个输入框不会被挡住
-(void)textViewDidBeginEditing:(UITextView *)textView
{
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.3f];
    CGRect frame = self.view.frame;
    frame.origin.y = frame.origin.y - INPUT_VIEW_OFFSET;
    self.view.frame = frame;
    [UIView commitAnimations];
}

//输入结束的时候把整个界面向下移动，这个能恢复正常
-(void)textViewDidEndEditing:(UITextView *)textView
{
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.3f];
    CGRect frame = self.view.frame;
    frame.origin.y = frame.origin.y + INPUT_VIEW_OFFSET;
    self.view.frame = frame;
    [UIView commitAnimations];
}

#pragma mark - Feedback Method
-(void)makeFeedBack
{
    NSString *content = _adviceTextView.text;
    if (!content || content.length == 0) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请输入反馈内容" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    [self startLoadingViewWithText:@"正在提交..."];
    [UserInfoService getUserInfoService].delegate = self;
    [[UserInfoService getUserInfoService] userFeedbackWithContent:content Practicality:self.practicability EaseUse:self.easeUsablity];
}

#pragma mark - Show WebView
-(void)showWebView:(NSString *)key
{
    NSString *url;
    NSString *title;
    if ([key isEqualToString:@"About"]) {
        url = @"about";
        title = @"关于";
    } else if ([key isEqualToString:@"Help"]) {
        url = @"help";
        title =@"帮助";
    }
    if (url && url.length > 0) {
        WebViewController *webVC = [[WebViewController alloc]initWithNibName:@"WebViewController" bundle:nil];
        //        webVC.url = url;
        webVC.title = title;
        webVC.name = url;
        [self.navigationController pushViewController:webVC animated:YES];
        //        [webVC loadFileWithName:url];
    }
}

#pragma mark - User Service Delegate
-(void)loadUserInfoFinished:(id)result
{
    [self stopLoadingView];
    self.adviceTextView.text = @"";
    //    self.practicabilitySegment.selectedSegmentIndex = 0;
    //    self.easeUsablitySegment.selectedSegmentIndex = 0;
}

-(void)loadUserInfoFaild:(NSString *)msg
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
    [self stopLoadingView];
    
}

#pragma mark - Data Service
-(void)loadDataFinished
{
    [self stopLoadingView];
    [_tableView reloadData];
}

-(void)loadDataFaild:(NSString *)msg
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
    [self stopLoadingView];
}

@end
